package jsonparser.core.parser;

import jsonparser.exception.JSONParseException;
import jsonparser.JSONArray;
import jsonparser.core.parser.nt.Value;

/**
 * Created by pendragon on 17-5-20.
 */
public class JSONArrayBuilder implements Builder<JSONArray>{

    private JSONArray array;
    private Value.ValueType type;

    public JSONArrayBuilder() {
        array = new JSONArray();
    }

    public JSONArray build() {
        return array;
    }

    public void addValue(Value value) throws JSONParseException {
        if (type == null)
            type = value.getType();

        switch (value.getType()) {
            case STRING:
                if (type == Value.ValueType.STRING) {
                    array.addValue(value.getValue());
                    return;
                }

                break;
            case NUMBER:
                if (type == Value.ValueType.NUMBER) {
                    array.addValue(value.getValue());
                    return;
                }

                break;
            case JSONOBJECT:
                if (type == Value.ValueType.JSONOBJECT) {
                    JSONObjectBuilder objectBuilder = (JSONObjectBuilder) value.getValue();
                    array.addValue(objectBuilder.build());
                    return;
                }

                break;
            case JSONARRAY:
                if (type == Value.ValueType.JSONARRAY) {
                    JSONArrayBuilder arrayBuilder = (JSONArrayBuilder) value.getValue();
                    array.addValue(arrayBuilder.build());
                    return;
                }

                break;
            case BOOLEAN:
                if (type == Value.ValueType.BOOLEAN) {
                    array.addValue(value.getValue());
                    return;
                }

                break;
            case NULL:
                if (type == Value.ValueType.NULL) {
                    array.addValue(null);
                    return;
                }

                break;
        }

        throw new JSONParseException("conflict type error");
    }
}
